package com.libui.thirdpartsdk.openinstall

import android.content.Intent
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import com.fm.openinstall.OpenInstall
import com.fm.openinstall.listener.AppInstallAdapter
import com.fm.openinstall.listener.AppWakeUpAdapter
import com.fm.openinstall.model.AppData
import com.libbase.extension.filterDuplicates
import com.libbase.utils.JsonUtils
import com.libbase.utils.genericType
import com.libnetwork.Network
import com.libui.BaseApplication
import com.libui.LibUI
import com.libui.thirdpartsdk.SDKInterface
import com.libui.thirdpartsdk.login.Login
import com.libui.thirdpartsdk.share.ShareInterface
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.addTo

class OpenInstallSDK : SDKInterface {
    companion object {
        val builder = object : SDKInterface.Builder {
            override val type: String = "openInstall"

            override val sdkVersion: String = OpenInstall.getVersion()

            override val loginBuilder: Login.Builder? = null

            override val shareBuilders: List<ShareInterface.Builder>? = null

            override fun build(): SDKInterface {
                return OpenInstallSDK()
            }
        }
    }

    override val type: String
        get() = builder.type

    override val loginBuilder: Login.Builder?
        get() = builder.loginBuilder

    override val shareBuilders: List<ShareInterface.Builder>?
        get() = builder.shareBuilders

    override val isAppInstalled: Boolean = false

    override val sdkVersion: String?
        get() = builder.sdkVersion

    private val compositeDisposable = CompositeDisposable()

    override fun install(): Boolean {
        return BaseApplication.instance?.let {
            OpenInstall.clipBoardEnabled(true)
            OpenInstall.init(it.baseContext)

            ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onCreate(owner: LifecycleOwner) {
                    super.onCreate(owner)

                    Network.instance
                        .reachabilityListener
                        .filterDuplicates(Network.NetworkReachabilityStatus.UNKNOWN)
                        .subscribe({ networkReachabilityStatus ->
                            if (!networkReachabilityStatus.isReachable) {
                                return@subscribe
                            }

                            OpenInstall.getInstall(object : AppInstallAdapter() {
                                override fun onInstall(appData: AppData) {
                                    LibUI.instance.adapter?.tracking(
                                        "getInstallParamsCompleted", makeParams(appData)
                                    )
                                }
                            })

                            compositeDisposable.dispose()
                        }, { error ->
                            error.printStackTrace()
                        })
                        .addTo(compositeDisposable)
                }
            })

            return true
        } ?: false
    }

    override fun uninstall() {
    }

    private fun makeParams(appData: AppData): Map<String, Any> {
        val params = mutableMapOf<String, Any>()

        if (appData.channel.isNotEmpty()) {
            params["channelCode"] = appData.channel
        }

        if (appData.data.isNotEmpty()) {
            params["data"] = JsonUtils.json.fromJson(appData.data, genericType<Map<String, Any>>())
        }

        return params
    }

    fun onOpenInstallWakeUp(appData: AppData) {
        LibUI.instance.adapter?.tracking("getWakeUpParams", makeParams(appData))
    }

    override fun handleIntent(intent: Intent): Boolean {
        return OpenInstall.getWakeUp(intent, object : AppWakeUpAdapter() {
            override fun onWakeUp(appData: AppData) {
                onOpenInstallWakeUp(appData)
            }
        })
    }
}